<template>
  <layout-card
    class="layoutCard"
    v-model="search"
    :filters="ismapOptions"
    headline="信息列表"
    headtitle="数据筛选"
    :hasButton="true"
    @search-change="getData"
    @search-reset="searchReset"
  >
    <template #action>
      <el-button type="primary" @click="handleCreate('threshold')">数量阈值</el-button>
      <el-button type="primary" @click="handleCreate('export')" :disabled="!tabledata.length">导出</el-button>
      <el-button type="primary" @click="handleCreate('download')">模版下载</el-button>
      <el-upload
        style="display: inline-block;margin-left: 12px;margin-right: 12px;"
        ref="upload"
        :auto-upload="false"
        :on-change="handleImport"
        :show-file-list="false"
        accept=".xlsx, .xls"
      >
        <el-button type="primary">导入</el-button>
      </el-upload>
      <!-- <el-button type="primary" @click="handleCreate('import')">导入</el-button> -->
      <el-button type="primary" @click="handleCreate('add')">新增设备</el-button>
    </template>
    <table-common
      stripe="true"
      :columns="mapListColumns"
      :loading="loading"
      :pagination="pager"
      :table-data="tabledata"
      size="large"
      @current-change="changeCurrent"
      @size-change="changePageSize"
    >
      <template #action="{ row }">
        <!-- 自定义操作栏示例  -->
        <el-button class="link-btn" @click="handleEdit(row)" link type="primary">编辑</el-button>
        <el-popconfirm
          title="是否删除?"
          confirmButtonText="确定"
          cancelButtonText="取消"
          @confirm="() => DeletRow(row)"
        >
          <template #reference>
            <el-button class="link-btn" link type="danger">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </table-common>
  </layout-card>
  <edit-dialog
    :close-on-click-modal="false"
    :centerDialogVisible="thresholdDialogVisible"
    :tilte="addTilte"
    :key="timer"
    :defaultButton="false"
    :width="500"
    style="height: 100px"
    @Cancel="handleCancel"
  >
    <template #content>
      <el-table :data="thresholdData" :pagination="false" height="200px" @row-click="hiddenMe">
        <el-table-column type="index" label="序号" width="60" align="center"/>
        <template v-for="(item, colIndex) in thresholdListColumns" :key="colIndex">
          <el-table-column :label="item.label" :prop="item.prop" :width="item.width" align="center">
            <template #default="scope">
              <el-input-number
                v-if="isEdit && scope.$index === rowInd && scope.cellIndex === colInd"
                v-model="scope.row[item.prop]"
                size="small"
                style="width: 80px"
                controls-position="right"
                @click.stop
              />
              <el-select
                v-else-if="isSelect && scope.$index === rowInd && scope.cellIndex === colInd"
                v-model="scope.row[item.prop]"
                size="small"
              >
                <el-option key="1" label="是" value="是" />
                <el-option key="2" label="否" value="否" />
              </el-select>
              <div
                v-else
                @click="cellClick(scope)"
                style="width: 50px; height: 24px"
              >{{ scope.row[item.prop] }}</div>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </template>

    <template #custom>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </span>
    </template>
  </edit-dialog>
  <!-- 地图弹窗 -->
  <edit-dialog
    :close-on-click-modal="false"
    :centerDialogVisible="addDialogVisible"
    :tilte="addTilte"
    :key="timer"
    :defaultButton="false"
    :width="950"
    style="height: 100px"
    @cancel="handleCancel"
  >
    <template #content>
      <div style="width: 100%; height: 500px; border: 1px solid #000">
        <map-control @mapClick="mapClick" @mapLoad="mapLoadEvent"></map-control>
      </div>
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button class="buttonCancel" @click="handleCancel">取消</el-button>
        <el-button class="buttonOk" type="primary" @click="handleNext">下一步</el-button>
        <el-button class="buttonOk" @click="handleNext" plain>跳过</el-button>
      </span>
    </template>
  </edit-dialog>
  <!-- 表单弹窗 -->
  <edit-dialog
    :close-on-click-modal="false"
    :centerDialogVisible="saveDialogVisible"
    :tilte="addTilte"
    :key="timer"
    :defaultButton="false"
    :width="950"
    style="height: 100px"
    :rules="rules"
    @cancel="handleCancel"
  >
    <template #content>
      <filter-bar
        :filters="isdialogOptions"
        :hasButton="false"
        :rules="rules"
        ref="FilterRef"
        :close-collapse="false"
        @on-toggle="(val) => $emit('on-toggle', val)"
      ></filter-bar>
    </template>

    <template #custom>
      <span class="dialog-footer">
        <el-button class="buttonCancel" @click="handleCancel">取消</el-button>
        <el-button class="buttonOk" @click="handleBack">返回</el-button>
        <el-button class="buttonOk" type="primary" @click="handleSave">保存</el-button>
      </span>
    </template>
  </edit-dialog>
</template>

<script lang="ts" setup>
import {
  computed,
  ref,
  reactive,
  watchEffect,
  onMounted,
  nextTick
} from "vue";
import LayoutCard from "@/components/LayoutCard/index.vue";
import TableCommon from "@/components/TableCommon/index.vue";
import editDialog from "@/components/editDialog/index.vue";
import {
  geteqptType,
  devicePageList,
  deviceDeleteRow,
  deviceModuleDown,
  deviceImport,
  exportPageList,
  append,
  change
} from "@/api/eqpt/strap";

import { getOrgInfo } from "@/api/user";
import {
  mapListColumns,
  thresholdListColumns
} from "@/views/eqpt/strap/config/columns";
import { mapOptions, dialogOptions } from "@/views/eqpt/strap/config/filters";
import { usePagination } from "vue-request";
import { FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import FilterBar from "@/components/FilterBar/index.vue";
import { getResource } from "@/api/resource";
import { UploadInstance } from "element-plus";
import { useStore } from "vuex";
import mapControl from "@/components/map/index.vue";
import { store } from "@/components/map/mapStore";
import { image } from "@/assets/index";
import { User } from "@element-plus/icons-vue/dist/types";
import { now } from "moment";

const isdialogOptions = ref(dialogOptions);

const mapList = new Map();
//请求用户的权限树
let { getters } = useStore();
// 拿到vuex里面用户的信息
const organInfo = computed(() => getters["user/getOrganTree"]);
// const Users = computed(() => getters["user/getUserInfo"]);
const typeId = "";

const stores = useStore();
const organTree = stores.state.user.organTree; //获取树
let organNameList = [];
if (organTree.length > 0) {
  organTree[0].children.forEach(organ => {
    let organObject = {
      name: organ.data.name,
      organId: organ.data.organId
    };
    organNameList.push(organObject);
  });
}

isdialogOptions.value.forEach(e => {
  if (e.prop == "useOrgans") {
    e.inputProps.options = [];
    organNameList.forEach(item => {
      let organNameObj = {
        label: item.name,
        value: item.organId
      };
      e.inputProps.options.push(organNameObj);
    });
  }
});

//使用部门Map对象
let organMap = new Map();
organNameList.forEach(item => {
  organMap.set(item.organId, item.name);
});

//StrapType:设备类型

const strapType = [];
if (organInfo.value.length > 0) {
  strapType = organInfo.value[0].children[0].children.map(
    ({ data: { organId, name } }) => ({ organId, name })
  );
}
let ownerList = [];
strapType.forEach(e => {
  const ownerObj = {
    label: e.name,
    value: e.organId
  };
  ownerList.push(ownerObj);
});

ownerList.forEach(e => {
  mapList.set(e.value, e.label);
});

const maplist = new Map();
const processNode = (node: any) => {
    const type = reactive<any>({
      value: node.data.organId,
      label: node.data.name,
      children: [],
    });
    if (node.children) {
      node.children.forEach((child: any) => {
        const ctype = reactive<any>({
          value: child.data.organId,
          label: child.data.name,
          children: [],
        });
        if (child.children) {
          child.children.forEach((subChild: any) => {
            const cctype = reactive<any>({
              value: subChild.data.organId,
              label: subChild.data.name,
            });
            ctype.children.push(cctype);
            maplist.set(subChild.data.organId, subChild.data.organId);
          });
        }
        type.children.push(ctype);
        maplist.set(child.data.name, child.data.name);
      });
    }
    return type;
  };



isdialogOptions.value.forEach(e => {
  if (e.prop == "owner") {
    // e.inputProps.options = ownerList;
    e.inputProps.data = [];
    organTree.forEach((entry: any) => {
      e.inputProps.data.push(processNode(entry));
    });
    e.events.change = function(value, evt) {
      geteqptType({ owners: [value] }).then(resq => {
        isdialogOptions.value.forEach(c => {
          if (c.prop == "eqptType") {
            FilterRef.value.setFieldsValue({
              eqptType: null
            });
            let arry = [];
            let items = [];
            let keyword = "拉带";
            const regex = new RegExp(keyword, "i"); // i表示不区分大小写
            resq.data.forEach((item, index) => {
              // if (regex.test(item.typeName)) {
                // children和label的值根据后端接口的实际情况书写
                c.inputProps.defaultProps = {
                  children: "children",
                  label: "typeName",
                  value: "typeId"
                };

                items.push(item);
                arry = items;
              // }
            });

            c.inputProps.data = arry;

            c.events.change = function(value, evt) {
              typeId = value;
            };
          }
        });
      });
    };
  }
});

const Id = ref(null);
const ismapOptions = ref(mapOptions);
ismapOptions.value[0].inputProps.options.unshift({
  label: "全部",
  value: "全部"
});
const thresholdDialogVisible = ref(false);
const addDialogVisible = ref(false);
const saveDialogVisible = ref(false);
const isEdit = ref(false);
const isSelect = ref(false);
const rowInd = ref(0);
const colInd = ref(0);
const timer = ref();
const addTilte = ref("");
var coordinate = null;
// 记得让columns.ts里面的对应thresholdListColumns的字段名和后端数据保持一致
const thresholdData = ref([]);
const CacheState = JSON.parse(
  window.localStorage.getItem("CacheState") as string
);
const name = ref("");
const userId = ref("");
const organId = ref("");
const organName = ref("");
name.value = CacheState.user.userInfo.name;
userId.value = CacheState.user.userInfo.userId;
organId.value = CacheState.user.userInfo.organId;
organName.value = CacheState.user.userInfo.organName;

//获取当前时间
const getCurrentTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = ("0" + (now.getMonth() + 1)).slice(-2);
  const day = ("0" + now.getDate()).slice(-2);
  const formattedTime = `${year}${month}${day}`;
  return formattedTime;
};
// 编辑栏处于 编辑 还是 增加 状态判断
var dialogState = "";

// const uploadedFiles = ref([]);
const upload = ref<UploadInstance>();
//导入
const handleImport = (file: any) => {
  const index = file.name.lastIndexOf("."); // 根据文件名找到最后一个‘.’的索引
  const suffixName = file.name.substr(index); // 根据索引截取，得到后缀名
  if (suffixName !== ".xlsx" && suffixName !== ".xls") {
    ElMessage({
      message: "此文件不是excel文件",
      type: "warning"
    });
    upload.value?.clearFiles();
  } else {
    const formData = new FormData();
    formData.append("multipartFile", file.raw);
    formData.append("id", userId.value);
    formData.append("name", name.value);
    formData.append("organId", organId.value);
    formData.append("organName", organName.value);

    deviceImport(formData)
      .then(res => {
        if (res.code == "1") {
          getData();
          ElMessage({
            message: "导入成功",
            type: "success"
          });
          // if (upload.value != null) {
          upload.value!.clearFiles();
          // }
        } else {
          ElMessage.error("导入失败");
          upload.value!.clearFiles();
        }
      })
      .catch(err => {
        ElMessage.error(err?.message || "导入失败");
        upload.value!.clearFiles();
      });
  }
};
const handleCreate = val => {
  timer.value = new Date().getTime();
  if (val === "threshold") {
    // 弹窗标题
    thresholdDialogVisible.value = true;
    addTilte.value = "设置维护提醒";
  } else if (val === "export") {
    //导出
    exportPageList(search?.value).then(res => {
      const a = document.createElement("a");
      a.href = URL.createObjectURL(new Blob([res]));
      a.download = `隔离带管理${getCurrentTime()}.xlsx`;
      a.click();
    });
  } else if (val === "download") {
    deviceModuleDown().then(res => {
      const a = document.createElement("a");
      a.href = URL.createObjectURL(new Blob([res]));
      a.download = "隔离拉带导入模板.xlsx";
      a.click();
    });
  } else if (val === "import") {
  } else {
    // 弹窗标题
    dialogState = "add";

    isdialogOptions.value.forEach(e => {
      e.defaultValue = "";
    });
    FilterRef.value = {};
    addTilte.value = "新增设施设备";
    //控制表单弹窗
    addDialogVisible.value = true;
  }
};

//点击地图坐标图标返回地图页面
isdialogOptions.value.forEach(e => {
  if (e.prop == "coordinate") {
    e.events.click = function(value, evt) {
      handleBack();
    };
  }
});

//递归遍历树
function flattenTree(tree) {
  var result = [];

  function flatten(node) {
    let item = {
      typeId: node.typeId,
      typeName: node.typeName
    };
    result.push(item);

    if (node.children && node.children.length > 0) {
      node.children.forEach(function(child) {
        flatten(child);
      });
    }
  }

  flatten(tree);

  return result;
}

let useOranList = "";
let rowOwner = "";
//点击编辑按钮
const handleEdit = row => {
  timer.value = new Date().getTime();
  addTilte.value = "编辑设施设备";
  dialogState = "edit";
  Id.value = row.eqptId;
  coordinate = row.coordinate;
  addDialogVisible.value = false;
  saveDialogVisible.value = true;
  // 该循环用于进行编辑页面数据回显，需要字段对应
  isdialogOptions.value.forEach(e => {
    if (e.prop == "useOrgans") {
      e.defaultValue = [];
      if (
        row.combinedOrganNames != " " &&
        row.combinedOrganNames != undefined
      ) {
        organMap.forEach((key, value) => {
          if (key == row.combinedOrganNames) {
            e.defaultValue = [value];
          }
        });
      }
    }
    if (row[e.prop] != null && e.prop != "eqptType") {
      e.defaultValue = row[e.prop];
    }
    if (e.prop == "eqptType") {
      mapList.forEach((key, value) => {
        if (key == row.ownerName) {
          //获取设备类型
          geteqptType({ owners: [value] }).then(resq => {
            isdialogOptions.value.forEach(c => {
              if (c.prop == "eqptType") {
                let arry = [];
                let items = [];
                let keyword = "拉带";
                FilterRef.value.setFieldsValue({
                  eqptType: null
                });
                const regex = new RegExp(keyword, "i"); // i表示不区分大小写
                resq.data.forEach((item, index) => {
                  // if (regex.test(item.typeName)) {
                    // children和label的值根据后端接口的实际情况书写
                    c.inputProps.defaultProps = {
                      children: "children",
                      label: "typeName",
                      value: "typeId"
                    };

                    items.push(item);
                    arry = items;
                  // }
                });

                c.inputProps.data = arry;

                FilterRef.value.setFieldsValue({
                      eqptType: row.typeId
                });

                //遍历的设备类型树
                // const nowData = flattenTree(arry[0]);
                // nowData.forEach(item => {
                //   if (item.typeId == row.typeId) {
                //     FilterRef.value.setFieldsValue({
                //       eqptType: item.typeName
                //     });
                //     typeId = row.typeId;
                //   }
                // });
                c.events.change = function(value, evt) {
                  typeId = value;
                };
              }
            });
          });
        }
      });
    }
    //坐标
    if (e.prop == "coordinate") {
      if ("coordinate" in row) {
        if (!row.coordinate?.latitude) {
          e.defaultValue = "";
        } else {
          e.defaultValue = `(${row.coordinate?.latitude || ""} , ${row
            .coordinate?.longitude || ""})`;
        }
      } else {
        e.defaultValue = "";
      }
    }
    //归属单位
    if (e.prop == "owner") {
      mapList.forEach((key, value) => {
        if (row.ownerName) {
          if (key == row.ownerName) {
            e.defaultValue = value;
          }
        } else {
          e.defaultValue = null;
        }
      });
      rowOwner = row.ownerName;
    }

    //位置
    if (e.prop == "position") {
      if (row.position == "undefined") {
        e.defaultValue = "";
      }
    }
  });
};
const handleSubmit = (k: any) => {
  isEdit.value= false;
  isSelect.value=false
  thresholdDialogVisible.value = false;
};
// 点击取消
const handleCancel = () => {
  isEdit.value= false;
  isSelect.value=false
  // 点取消 地图清空
  vcoordinate.value = "";
  //清空设备类型选项
  isdialogOptions.value.forEach(e => {
    if (e.prop == "eqptType") {
      e.inputProps.data = [];
    }
  });

  mapPoint.value.latitude = ""
  mapPoint.value.longitude = ""
  thresholdDialogVisible.value = false;
  addDialogVisible.value = false;
  saveDialogVisible.value = false;
};
let nowData = ref({});
// 点击下一步
const handleNext = () => {
  addDialogVisible.value = false;
  saveDialogVisible.value = true;
  isdialogOptions.value.forEach(e => {
    if (e.prop == "coordinate") {
      if (mapPoint.value.latitude) {
        // e.defaultValue = `(${mapPoint.value.latitude} , ${mapPoint.value.longitude})`;
        e.defaultValue = vcoordinate.value;
      } else {
        FilterRef.value?.setFieldsValue({
          coordinate: ""
        });
      }
    }
  });

  if (vcoordinate.value) {
    nextTick(() => {
      FilterRef.value.setFieldsValue({
        coordinate: vcoordinate.value
      });
    });
  }
  if (Object.keys(nowData.value).length) {
    isdialogOptions.value.forEach(item => {
      if (item.prop == "eqptCode") {
        item.defaultValue = nowData.value?.eqptCode || "";
      }
      if (item.prop == "eqptModel") {
        item.defaultValue = nowData.value?.eqptModel || "";
      }
      if (item.prop == "eqptName") {
        item.defaultValue = nowData.value?.eqptName || "";
      }
      if (item.prop == "position") {
        item.defaultValue = nowData.value?.position || "";
      }
      if (item.prop == "coordinate") {
        item.defaultValue = nowData.value?.coordinate || "";
      }
      if (item.prop == "useOrgans") {
        item.defaultValue = nowData.value?.useOrgans || [];
      }
      if (item.prop == "owner") {
        item.defaultValue = nowData.value?.owner || "";
      }
      if (item.prop == "eqptType") {
        item.defaultValue = nowData.value.eqptType;
      }
    });
  }
};
// 点击返回
const handleBack = async () => {
  saveDialogVisible.value = false;
  addDialogVisible.value = true;
  nowData.value = FilterRef.value.getParams();
  let location = nowData.value.coordinate.split(',');
  mapPoint.value.latitude = location[0].substr(1).trim();
  mapPoint.value.longitude = location[1].substr(0, location[1].length-1).trim();
};

const mapLoadEvent = () => {
  if (mapPoint.value.latitude !== "") {
    store.BNMap.removeGraphicsLayer("clickLayer")
    // 向地图添加临时图层
    const clickLayer = store.BNMap.creatGraphicsLayer({ id: "clickLayer" })
    clickLayer.removeAll()
    // 创建点
    const point = store.BNMap.createPoint({
      x: mapPoint.value.latitude,
      y: mapPoint.value.longitude,
      spatialReference: store.BNMap.spatialReference,
    })
    store.BNMap.setCenter(point)
    // 创建图片
    const symbolStyle = store.BNSymbol.PictureMarkerSymbol(image.point, 20, 20)
    // 创建要素
    const picgraphic = store.BNMap.graphic(point, symbolStyle)
    // 添加到地图
    clickLayer.add(picgraphic)
    store.BNMap.addGraphicsLayer(clickLayer)
  }
};

const content = ref([]);

const FilterRef = ref({});

// 点击保存
const handleSave = async () => {
  let flag = await FilterRef.value?.validateRuleFormRef();
  if (flag) {
    const data = FilterRef.value.getParams();
    //归属单位
    data.owner = {
      id: data.owner,
      name: mapList.get(data.owner)
    };
    //位置
    if (data.position == undefined) {
      data.position = "";
    }
    //设备型号
    if (data.eqptModel == undefined) {
      data.eqptModel = "";
    }

    //地图坐标
    if (Object.keys(mapPoint.value).latitude === '') { //地图上没有选择位置
      if(dialogState == "add"){
        data.coordinate = " ";
      }else{
        let location = data.coordinate.split(',');
        data.coordinate = {latitude: location[0].substr(1).trim(), longitude:location[1].substr(0, location[1].length-1).trim()};
      }
    } else {
      let location = FilterRef.value.getParams().coordinate.split(',')
      data.coordinate = {latitude: location[0].substr(1).trim(), longitude:location[1].substr(0, location[1].length-1).trim()};
    }
    //使用部门
    const use = data.useOrgans;
    data.useOrgans = [];
    if (use.length) {
      for (let i of use) {
        data.useOrgans.push({
          organName: organMap.get(i)
        });
      }
    } else {
      data.useOrgans.push({
        organName: " "
      });
    }

    data.eqptType = 1;
    // 数据库非空字段
    data.typeId = typeId;

    if (dialogState == "add") {
      for (let el of data) {
        if (typeof el === "string") {
          el = el.trim();
        }
      }
      append(data)
        .then(res => {
          if (res.code == "1") {
            ElMessage({
              message: "添加成功",
              type: "success"
            });
            getData();
          } else {
            ElMessage.error("添加失败");
          }
          //清空设备类型下拉框数据
          isdialogOptions.value.forEach(e => {
            if (e.prop == "eqptType") {
              e.inputProps.data = [];
            }
          });
          //关闭弹窗
          saveDialogVisible.value = false;
        })
        .catch(err => {
          ElMessage.error(err?.message || "保存失败");
        });
    } else {
      data.eqptId = Id.value;
      //请求修改数据
      for (let el of data) {
        if (typeof el === "string") {
          el = el.trim();
        }
      }
      change(data).then(res => {
        if (res.code == "1") {
          ElMessage({
            message: "编辑成功",
            type: "success"
          });
          getData();
        } else {
          ElMessage.error("编辑失败");
        }
        //清空设备类型下拉框数据
        isdialogOptions.value.forEach(e => {
          if (e.prop == "eqptType") {
            e.inputProps.data = [];
          }
        });
        //关闭弹窗
        saveDialogVisible.value = false;
      });
    }

    handleCancel();
  }
};

const vcoordinate = ref("");

const mapClick = (evt: any) => {
  store.BNMap.removeGraphicsLayer("clickLayer");
  // 向地图添加临时图层
  const clickLayer = store.BNMap.creatGraphicsLayer({ id: "clickLayer" });
  clickLayer.removeAll();
  // 创建点
  const point = store.BNMap.createPoint({
    x: evt.mapPoint.x,
    y: evt.mapPoint.y,
    spatialReference: evt.mapPoint.spatialReference
  });
  // store.BNMap.setCenter(point);
  // 创建图片
  const symbolStyle = store.BNSymbol.PictureMarkerSymbol(image.point, 20, 25);
  // 创建要素
  const picgraphic = store.BNMap.graphic(point, symbolStyle);
  // 添加到地图
  clickLayer.add(picgraphic);
  store.BNMap.addGraphicsLayer(clickLayer);
  // 将相关信息保存到变量
  mapPoint.value.latitude = evt.mapPoint.x;
  mapPoint.value.longitude = evt.mapPoint.y;
  // 地图区域值暂时为空

  isdialogOptions.value.forEach(e => {
    if (e.prop == "coordinate") {
      e.defaultValue = `(${mapPoint.value.latitude} , ${mapPoint.value.longitude})`;
      e.value = `(${mapPoint.value.latitude} , ${mapPoint.value.longitude})`;
      vcoordinate.value = `(${mapPoint.value.latitude} , ${mapPoint.value.longitude})`;
    }
  });
};
const mapPoint = ref({
  longitude: "",
  latitude: ""
});

const rules = reactive({
  eqptCode: [{ required: true, message: "请输入设备编号", trigger: "change" }],
  eqptType: [{ required: true, message: "请选择设备类型", trigger: "change" }],
  eqptName: [{ required: true, message: "请输入设备名称", trigger: "change" }],
  owner: [{ required: true, message: "请选择归属单位", trigger: "change" }]
});

const current = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tabledata = ref([]);
const search = ref({});

const pager = computed(() => ({
  currentPage: current.value,
  pageSize: pageSize.value,
  total: total.value,
  pageCount: Math.ceil(total.value / pageSize.value) || 1
}));

//分页
const changeCurrent = (value: number) => {
  current.value = value;
  getData();
};
const changePageSize = (size: number) => {
  pageSize.value = size;
  getData();
};

// 获取数据
const getData = () => {
  const searchList = {
    eqptCode: search.value?.eqptCode,
    regions: search.value?.regions,
    terminal: search.value?.terminal,
    order: [
      {
        column: "eqptCode",
        method: "desc"
      }
    ]
  };
  const playout = {
    pageNum: current.value,
    pageSize: pageSize.value,
    condition: searchList
  };
  devicePageList(playout)
    .then(res => {
      tabledata.value = res?.data?.list;

      total.value = res?.data?.total;
    })
    .catch(err => {
      ElMessage.error(err?.message || "获取失败");
    });
};

//删除
const DeletRow = (row: any) => {
  const formData = new FormData();
  formData.append("eqptId", row.eqptId);
  const code = deviceDeleteRow(formData);
  code.then(res => {
    if (res?.code) {
      ElMessage({
        message: "删除成功",
        type: "success"
      });
      getData();
    } else {
      ElMessage.error("删除失败");
    }
  });
};

// 单击 出现输入框
// setThreshold 和 isAlarm 的字段名和后端数据保持一致
const cellClick = (val: any) => {
  if (val.column.property === "setThreshold") {
    isEdit.value = true;
    isSelect.value = false;
    rowInd.value = val.$index;
    colInd.value = val.cellIndex;
  } else if (val.column.property === "isAlarm") {
    isSelect.value = true;
    isEdit.value = false;
    rowInd.value = val.$index;
    colInd.value = val.cellIndex;
  }
};
const hiddenMe = (row, column, event) => {
  if (column != undefined) {
    isEdit.value = false;
    isSelect.value = false;
  }
};

// 该功能需要完成
const Submit = () => {};
//清空
const searchReset = (data: FilterDataType) => {
  search.value = data;
  search.value["regions"].checkAll = false;
  pager.value.currentPage = 1;
  pager.value.pageSize = 10;
  getData();
};

//获取terminal字典
const getTerminal = async (data: any) => {
  await getResource(data).then(res => {
    for (let i = 0; i <= ismapOptions.value.length; i++) {
      if (ismapOptions.value[i] && ismapOptions.value[i].prop === "terminal") {
          ismapOptions.value[i].inputProps.options = res.data.properties.meta;
      }
    }
  });
};

//获取区域数据字典
const getArea = async (data: any) => {
  await getResource(data).then(res => {
    let regions = res.data.properties.meta;
    for(let i = 0; i < regions.length; i++){
      var region  = {
        id: i,
        area: regions[i].label,
        historicalAverage: "30",
        isAlarm: regions[i].alert?"是":"否",
        setThreshold: "13"
      };
      thresholdData.value.push(region);
    }

    for (let i = 0; i < ismapOptions.value.length; i++) {
      if (ismapOptions.value[i] && ismapOptions.value[i].prop == "regions") {
        res.data.properties.meta.unshift({ label: "全部", value: "" });
        ismapOptions.value[i].inputProps.options = res.data.properties.meta;
        ismapOptions.value[i].inputProps.options[1].alert = true;
      }
    }
  });
};

onMounted(() => {
  getData();
  getTerminal("terminal");
  getArea("resource_area");
});
</script>

<style scoped>
.layoutCard /deep/ .el-form-item__label:nth-child(1) {
  width: 110px !important;
}
</style>
